package xuegao.study.mall.rbac.service.impl;

import cn.hutool.core.collection.CollUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xuegao.study.mall.common.domain.UserDto;
import xuegao.study.mall.common.dto.rbac.UmsMemberRegisterDto;
import xuegao.study.mall.common.model.ums.UmsMember;
import xuegao.study.mall.common.model.ums.UmsMemberLevel;
import xuegao.study.mall.rbac.service.UmsMemberService;
import xuegao.study.mall.repo.dao.ums.UmsMemberDao;
import xuegao.study.mall.repo.dao.ums.UmsMemberLevelDao;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UmsMemberServiceImpl implements UmsMemberService {

   @Autowired
   private UmsMemberDao umsMemberDao;

   @Resource
   private UmsMemberLevelDao umsMemberLevelDao;

    @Override
    public int register(UmsMemberRegisterDto memberDto) {
        // 1.验证码的验证逻辑

        // 2.查询该用户是否存在
        Map<String, Object> params1 = new HashMap<>();
        params1.put("username", memberDto.getUsername());
        List<UmsMember> umsMembers = umsMemberDao.selectByMap(params1);
        if (CollUtil.isNotEmpty(umsMembers)) {
            throw new RuntimeException("该用户已经存在");
        }
        // 3.没有该用户的话进行添加操作
        UmsMember member = new UmsMember();
        member.setUsername(memberDto.getUsername());
        member.setPassword(memberDto.getPassword());
        member.setPhone(memberDto.getTelephone());
        member.setCreateTime(new Date());
        member.setStatus(1);
        // 4.设置会员等级
        Map<String, Object> params2 = new HashMap<>();
        params2.put("default_status", 1);
        UmsMemberLevel defaultMemberLevel = umsMemberLevelDao.selectByMap(params2).get(0);
        member.setMemberLevelId(defaultMemberLevel.getId());
        return umsMemberDao.insert(member);
    }

    @Override
    public UserDto getUserByUsername(String username) {
        Map<String, Object> params = new HashMap<>();
        params.put("username", username);
        List<UmsMember> umsMembers = umsMemberDao.selectByMap(params);
        if (CollUtil.isNotEmpty(umsMembers)) {
            UmsMember member = umsMembers.get(0);
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(member, userDto);
            return userDto;
        }
        return null;
    }
}
